﻿// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. 
// See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneGroceryList.Resources;

namespace PhoneGroceryList
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Creates a CloudList<GroceryItem> and posts back a delegate to do the databinding on the UI thread.
            App.InitializeGroceriesAsync(GroceryItemsListBox);
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/NewItem.xaml", UriKind.Relative));
        }

        private void BoughtButton_Click(object sender, RoutedEventArgs e)
        {
            if (GroceryItemsListBox.SelectedIndex < 0)
                return;

            App.Groceries.RemoveAt(GroceryItemsListBox.SelectedIndex);
        }

        private async void ResetButton_Click(object sender, RoutedEventArgs e)
        {
            if (App.Groceries == null)
                return;  // Avoid a race where someone attempts to click on this button before our grocery list is initialized.

            // We can call either Clear() or await ClearAsync().  We should await async operations to ensure we do not block the UI thread.
            await App.Groceries.ClearAsync();
            App.AddDefaultItems();
        }
    }
}